package top.csjss.hospital.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import top.csjss.hospital.entity.SysUser;
import top.csjss.hospital.service.SysUserService;

/**
 * @Author ztf
 * @Date 11:30 2021/10/15
 **/
public class HospitalRealm extends AuthorizingRealm {
    public static final int HASH_ITERATIONS = 1024;
    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(HASH_ITERATIONS);
        this.setCredentialsMatcher(matcher);
    }
    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginName = (String) authenticationToken.getPrincipal();

        //根据用户名查询
        SysUser sysUser = sysUserService.findByLoginName(loginName);

        //判断查询结果
        if (sysUser == null) {
            throw new RuntimeException("【登录功能】用户名不正确");
        }
        //封装返回结果
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPwd(), "HospitalRealm");

        //设置盐
        info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getSalt()));

        return info;
    }
}
